package com.cinema.servlet.booking;

import com.cinema.dao.OrderDAO;
import com.cinema.entity.Order;
import com.cinema.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 支付成功页面Servlet
 */
public class PaymentSuccessServlet extends HttpServlet {
    private OrderDAO orderDAO = new OrderDAO();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String orderNo = request.getParameter("orderNo");
        
        if (orderNo == null || orderNo.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/user/orders");
            return;
        }
        
        try {
            // 获取订单信息
            Order order = orderDAO.findByOrderNo(orderNo);
            if (order == null) {
                request.setAttribute("error", "订单不存在");
                request.getRequestDispatcher("/error/404.jsp").forward(request, response);
                return;
            }
            
            // 检查订单所有者
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if (!order.getUserId().equals(user.getId())) {
                request.setAttribute("error", "无权访问此订单");
                request.getRequestDispatcher("/error/403.jsp").forward(request, response);
                return;
            }
            
            // 检查订单状态
            if (!"PAID".equals(order.getStatus())) {
                response.sendRedirect(request.getContextPath() + "/user/orders");
                return;
            }
            
            request.setAttribute("order", order);
            request.getRequestDispatcher("/payment-success.jsp").forward(request, response);
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取订单信息失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}
